import { TASK_RESULT_DB_PATH } from "../../constants";
import {
  TaskResultDBSchema,
  BuildTaskResult,
} from "../model/TaskResultDBSchema";
import { LowWithLodash } from "../model/DBWithLodash";
import { DBService } from "./DBService";
import { defaultTaskResultSchema } from "../../constants/schema";

export class BuildTaskResultService extends DBService {
  #dbIns: LowWithLodash<TaskResultDBSchema> | null = null;
  async init() {
    const db = await super.init(TASK_RESULT_DB_PATH, defaultTaskResultSchema);
    this.#dbIns = db;
    return db;
  }

  async list(filter?: (value: BuildTaskResult, index: number) => boolean) {
    return this.#dbIns?.chain.get("data").filter(filter).value() || [];
  }

  async add(rec: BuildTaskResult) {
    return await this.#dbIns?.update(({ data }) => {
      data.push(rec);
    });
  }

  /**
   * 清理所有数据，慎用
   * @returns
   */
  async clearAll() {
    return await this.#dbIns?.update((v) => {
      v.data = [];
    });
  }

  /**
   * 删除指定任务
   * @param taskId
   * @returns
   */
  async deleteById(taskId: string) {
    return await this.#dbIns?.update((v) => {
      v.data = v.data.filter((val) => val.taskId !== taskId);
    });
  }
}

export const buildTaskResultService = new BuildTaskResultService();
